package com.sxz.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sxz.mall.common.constant.ProductConstant;
import com.sxz.mall.product.dao.AttrAttrgroupRelationDao;
import com.sxz.mall.product.dao.AttrGroupDao;
import com.sxz.mall.product.entity.*;
import com.sxz.mall.product.service.AttrAttrgroupRelationService;
import com.sxz.mall.product.service.AttrGroupService;
import com.sxz.mall.product.service.CategoryService;
import com.sxz.mall.product.vo.AttrGroupRelationVO;
import com.sxz.mall.product.vo.AttrResponseVO;
import com.sxz.mall.product.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxz.mall.common.utils.PageUtils;
import com.sxz.mall.common.utils.Query;

import com.sxz.mall.product.dao.AttrDao;
import com.sxz.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVO attr) {

        // 保存规格参数
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        System.out.println("保存属性信息前: " + attrEntity);
        this.save(attrEntity);
        System.out.println("保存属性信息后: " + attrEntity);

        // 保存规格参数和属性组对应信息
        if (attrEntity.getAttrId() != null &&
                attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 封装对应的属性关系实体
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attr.getAttrGroupId());
            entity.setAttrId(attrEntity.getAttrId());

            attrAttrgroupRelationService.save(entity);
        }

    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long cateLogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
        if (cateLogId != 0) {
            wrapper.eq("catelog_id", cateLogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils resPage = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVO> list = records.stream().map((attrEntity) -> {
            AttrResponseVO responseVO = new AttrResponseVO();
            // 拷贝属性
            BeanUtils.copyProperties(attrEntity, responseVO);
            // 获取分类名称
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                responseVO.setCatelogName(categoryEntity.getName());
            }

            // 先找属性-属性组中间表，再找属性组名称
            // 封装查找条件
//            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
//            relationEntity.setAttrId(attrEntity.getAttrId());
            // dao查找
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity entity = attrAttrgroupRelationService
                        .getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));

                System.out.println("查找到的中间表数据: " + entity);

                if (entity != null && entity.getAttrGroupId() != null) {
                    AttrGroupEntity groupEntity = attrGroupService.getById(entity.getAttrGroupId());
                    responseVO.setGroupName(groupEntity.getAttrGroupName());
                }
            }

            return responseVO;
        }).collect(Collectors.toList());

        resPage.setList(list);

        return resPage;
    }

    @Override
    public AttrResponseVO getInfoById(Long attrId) {
        AttrResponseVO responseVO = new AttrResponseVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, responseVO);
        // attrGroupId缺失,需要查中间表
        if (attrEntity != null) {
            System.out.println("属性id对应的类型，integer" + attrEntity.getAttrType());
            if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                        .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if (groupEntity != null) {
                        responseVO.setGroupName(groupEntity.getAttrGroupName());
                        responseVO.setAttrGroupId(groupEntity.getAttrGroupId());
                    }
                }
            }
            // 查询关联的类别信息
            Long catelogId = attrEntity.getCatelogId();
            Long[] catelogPath = categoryService.findCatelogPath(catelogId);
            responseVO.setCatelogPath(catelogPath);

            CategoryEntity categoryEntity = categoryService.getById(catelogId);
            if (categoryEntity != null) {
                responseVO.setCatelogName(categoryEntity.getName());
            }
        }

        return responseVO;
    }

    @Override
    public void updateInfo(AttrVO attr) {
        // 更新属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        // 更新属性属性组中间表
        if (attr.getAttrGroupId() != null && attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer count = attrAttrgroupRelationDao
                    .selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                // 已经有绑定了，就更新
                attrAttrgroupRelationDao
                        .update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Transactional
    @Override
    public void removeByIdsDetails(Long[] attrIds) {
        // 如果是基本属性，需要删除中间表
        for (Long attrId : attrIds) {
            AttrEntity attrEntity = this.getById(attrId);
            if (attrEntity != null &&
                    attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                System.out.println("是基本属性，删除的属性id：" + attrId);
                attrAttrgroupRelationDao.delete(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            }
        }
        this.removeByIds(Arrays.asList(attrIds));
    }

    /**
     * 根据属性组编号查询基本信息
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        // 1、查询出关联的中间表
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrGroupId));

        // 2、根据属性id数组获取详细信息  map内部调接口
        List<AttrEntity> attrList = relationList.stream().map(entity -> this.getById(entity.getAttrId()))
                .collect(Collectors.toList());
        return attrList;
    }

    /**
     * 解除属性属性组关联关系
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        System.out.println("获取到需要删除的参数：");
        for (AttrGroupRelationVO vo : vos) {
            System.out.println(vo.getAttrId());
            System.out.println(vo.getAttrGroupId());
        }

        // 批量删除，单独在dao写方法实现，提高效率，采用循环，性能低
        List<AttrAttrgroupRelationEntity> entityList = Arrays.asList(vos).stream().map((item) -> {
            // 处理成entity，用于对接数据库
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(entityList);
        // todo 换接口试试
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {

        // 根据属性组id查询属性组实体
        AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupId);
        // 获取到分类id
        Long catelogId = groupEntity.getCatelogId();
        //找到该分类下的所有分组信息
        List<AttrGroupEntity> groupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        // 过滤出属性组列表的编号集合
        List<Long> groupIdList = groupList.stream()
                .map(item -> item.getAttrGroupId())
                .collect(Collectors.toList());
        // 查询属性属性组中间表已经分配的列表, 过滤出属性id列表
        List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", groupIdList));
        List<Long> attrIdList = entityList.stream().map(item -> item.getAttrId())
                .collect(Collectors.toList());
        // 分页查询的条件逻辑
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        // 添加排除条件
        if (attrIdList != null && attrIdList.size() > 0) {
            wrapper.notIn("attr_id", attrIdList);
        }
        // 根据key查询操作
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        // 查询对应的列表
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<AttrEntity> list = this.list(new QueryWrapper<AttrEntity>()
                .in("attr_id", attrIds).eq("search_type", 1));
        return list.stream().map(item->{
            return item.getAttrId();
        }).collect(Collectors.toList());
    }

}